package com.tensquare.article.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.pojo.Article;
import com.tensquare.article.service.ArticleService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RequestMapping("article")
@RestController
@CrossOrigin
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    //查询所有
    @GetMapping("/findAll")
    public Result findAll(){
        List<Article> articles = articleService.findAll();
        return new Result(true, StatusCode.OK, "查询成功", articles);
    }

    //根据ID查询
    @GetMapping("/{id}")
    public Result findById(String id){
        Article article = articleService.findById(id);
        return new Result(true, StatusCode.OK, "查询成功", article);
    }

    //添加文章
    @PostMapping
    public Result add(@RequestBody Article article){
        articleService.add(article);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    //更新文章
    @PutMapping("{id}")
    public Result update(@PathVariable String id, @RequestBody Article article){
        article.setId(id);
        articleService.update(article);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    //删除文章
    @DeleteMapping("{id}")
    public Result delete(@PathVariable String id){
        articleService.delete(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    //条件分页查询
    @PostMapping("/search/{page}/{size}")
    public Result search(@RequestBody Map map, //@RequestBody是查询条件
                         @PathVariable Integer page,
                         @PathVariable Integer size){

        Page<Article> pageData = articleService.search(map, page, size);
        PageResult<Article> pageResult = new PageResult<>(
                pageData.getTotal(), pageData.getRecords()
        );

        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    @GetMapping("/exception")
    public Result exception() throws Exception{
        throw new Exception("测试统一异常处理");
    }

}
























